#pragma once

#include <QAbstractTableModel>
#include "dbclinethandler.h"

class RemoteTableModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    explicit RemoteTableModel(const QString &tableName,
                              std::shared_ptr<DBClientThreadHandler> client,
                              QObject *parent = nullptr);

    // 基本模型接口
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override;

    // 分页相关
    void setPageSize(int size);
    int totalCount() const;

    /// @brief  加载指定页数据
    /// @param page
    void loadPage(int page);
    /// @brief 初始化表头
    /// @param columnMapping
    /// @param columnOrder
    void initHeader(const QMap<QString, QString> &columnMapping, const QStringList &columnOrder);
    /// @brief 获取表名
    QString getTableName() const;
    /// @brief  获取ID(主键)
    QString getID(int row) const;
    /// @brief  获取行数据
    QVariantMap getRowData(int row) const;

    /// @brief 刷新数据-查
    void refresh(const QString &filter = QString());
    /// @brief  删除行-删
    bool removeRow(int row, const QString &sql);
    /// @brief  插入行-增
    bool insertRow(const QVariantMap &data);
    /// @brief 增 -  用于关联式表插入
    void insertRowWithCallback(const QVariantMap &data, std::function<void(int)> callback);
    /// @brief 更新行-改
    bool updateRow(const QString &id, const QVariantMap &data);
    /// @brief  更新加载状态-重连后置为false
    void updateLoadState(bool loading) { m_loading = loading; }
    std::shared_ptr<DBClientThreadHandler> getClient() const { return m_client; }
    QStringList columnOrder() const { return COLUMN_ORDER; }
    QMap<QString, QString> columnMapping() const { return COLUMN_MAPPING; }
signals:
    void dataRefreshed();
    void loadFinished(const QVector<QVariantMap> &records);

public slots:
    ///  @brief 数据加载完成
    /// @param records 数据
    /// @param totalCount 总记录数
    void handleDataLoaded(const QVector<QVariantMap> &records);

private:
    /// @brief 表名
    QString m_tableName;
    /// @brief 数据库客户端线程处理器
    std::shared_ptr<DBClientThreadHandler> m_client;
    /// @brief 总数据
    QVector<QVariantMap> m_records;
    /// @brief 表头
    QVector<QString> m_headers;
    /// @brief 过滤条件
    QString m_filter;
    /// @brief 分页大小
    int m_pageSize;
    /// @brief 当前页码
    int m_currentPage;
    /// @brief 总行数
    int m_totalCount;
    /// @brief 总页数
    int m_totalPages;
    /// @brief 是否正在加载中-锁
    std::atomic<bool> m_loading{false};
    ///  @brief 英文键名到中文表头的映射
    QMap<QString, QString> COLUMN_MAPPING;
    /// @brief 表头显示顺序
    QStringList COLUMN_ORDER;
};